/*
 * @Author: Kiro AI Assistant
 * @Date: 2025-01-10
 * @Description: 专辑封面组件 - 优化图片加载和缓存
 */

import 'package:flutter/material.dart';
import 'package:cached_network_image/cached_network_image.dart';
import '../../models/music_item_model.dart';

/// 专辑封面组件
/// 使用 CachedNetworkImage 实现图片缓存，优化加载性能
class AlbumCoverWidget extends StatelessWidget {
  /// 音乐数据
  final MusicItemModel? music;

  /// 图片URL（优先级高于music.albumArt）
  final String? imageUrl;

  /// 组件宽度
  final double? width;

  /// 组件高度
  final double? height;

  /// 圆角半径
  final double borderRadius;

  /// 占位符图标
  final IconData placeholderIcon;

  /// 占位符图标大小
  final double placeholderIconSize;

  /// 占位符背景色
  final Color? placeholderColor;

  /// 是否显示阴影
  final bool showShadow;

  /// 阴影颜色
  final Color? shadowColor;

  /// 阴影模糊半径
  final double shadowBlurRadius;

  /// 阴影偏移
  final Offset shadowOffset;

  /// 图片适配方式
  final BoxFit fit;

  /// 点击回调
  final VoidCallback? onTap;

  /// 是否启用英雄动画
  final bool enableHeroAnimation;

  /// 英雄动画标签
  final String? heroTag;

  const AlbumCoverWidget({
    super.key,
    this.music,
    this.imageUrl,
    this.width,
    this.height,
    this.borderRadius = 8.0,
    this.placeholderIcon = Icons.music_note,
    this.placeholderIconSize = 48.0,
    this.placeholderColor,
    this.showShadow = true,
    this.shadowColor,
    this.shadowBlurRadius = 8.0,
    this.shadowOffset = const Offset(0, 4),
    this.fit = BoxFit.cover,
    this.onTap,
    this.enableHeroAnimation = false,
    this.heroTag,
  });

  @override
  Widget build(BuildContext context) {
    final effectiveImageUrl = imageUrl ?? music?.albumArt;
    final effectiveWidth = width ?? 120.0;
    final effectiveHeight = height ?? effectiveWidth;

    Widget coverWidget = Container(
      width: effectiveWidth,
      height: effectiveHeight,
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(borderRadius),
        boxShadow: showShadow
            ? [
                BoxShadow(
                  color: shadowColor ?? Colors.black.withOpacity(0.2),
                  blurRadius: shadowBlurRadius,
                  offset: shadowOffset,
                ),
              ]
            : null,
      ),
      child: ClipRRect(
        borderRadius: BorderRadius.circular(borderRadius),
        child: _buildImageContent(context, effectiveImageUrl),
      ),
    );

    // 如果启用英雄动画，包装 Hero 组件
    if (enableHeroAnimation && heroTag != null) {
      coverWidget = Hero(
        tag: heroTag!,
        child: coverWidget,
      );
    }

    // 如果有点击回调，包装 GestureDetector
    if (onTap != null) {
      coverWidget = GestureDetector(
        onTap: onTap,
        child: coverWidget,
      );
    }

    return coverWidget;
  }

  /// 构建图片内容
  Widget _buildImageContent(BuildContext context, String? imageUrl) {
    if (imageUrl != null && imageUrl.isNotEmpty) {
      return CachedNetworkImage(
        imageUrl: imageUrl,
        fit: fit,
        placeholder: (context, url) => _buildPlaceholder(context),
        errorWidget: (context, url, error) => _buildErrorWidget(context),
        // 缓存配置
        cacheKey: imageUrl,
        memCacheWidth: (width?.toInt() ?? 120) * 2, // 2x 分辨率缓存
        memCacheHeight: (height?.toInt() ?? 120) * 2,
        maxWidthDiskCache: 400, // 磁盘缓存最大宽度
        maxHeightDiskCache: 400, // 磁盘缓存最大高度
        // 渐入动画
        fadeInDuration: const Duration(milliseconds: 300),
        fadeOutDuration: const Duration(milliseconds: 100),
      );
    } else {
      return _buildPlaceholder(context);
    }
  }

  /// 构建占位符
  Widget _buildPlaceholder(BuildContext context) {
    return Container(
      color: placeholderColor ?? Colors.grey.shade200,
      child: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(
              placeholderIcon,
              size: placeholderIconSize,
              color: Colors.grey.shade400,
            ),
            if (music?.title != null) ...[
              const SizedBox(height: 8),
              Padding(
                padding: const EdgeInsets.symmetric(horizontal: 8),
                child: Text(
                  music!.title,
                  style: TextStyle(
                    fontSize: 12,
                    color: Colors.grey.shade600,
                    fontWeight: FontWeight.w500,
                  ),
                  textAlign: TextAlign.center,
                  maxLines: 2,
                  overflow: TextOverflow.ellipsis,
                ),
              ),
            ],
          ],
        ),
      ),
    );
  }

  /// 构建错误组件
  Widget _buildErrorWidget(BuildContext context) {
    return Container(
      color: Colors.grey.shade100,
      child: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(
              Icons.broken_image,
              size: placeholderIconSize,
              color: Colors.grey.shade400,
            ),
            const SizedBox(height: 4),
            Text(
              '加载失败',
              style: TextStyle(
                fontSize: 10,
                color: Colors.grey.shade500,
              ),
            ),
          ],
        ),
      ),
    );
  }
}

/// 圆形专辑封面组件
/// 适用于播放器页面的主要专辑封面显示
class CircularAlbumCoverWidget extends StatelessWidget {
  /// 音乐数据
  final MusicItemModel? music;

  /// 图片URL
  final String? imageUrl;

  /// 组件大小
  final double size;

  /// 边框宽度
  final double borderWidth;

  /// 边框颜色
  final Color? borderColor;

  /// 是否显示阴影
  final bool showShadow;

  /// 点击回调
  final VoidCallback? onTap;

  /// 是否启用英雄动画
  final bool enableHeroAnimation;

  /// 英雄动画标签
  final String? heroTag;

  const CircularAlbumCoverWidget({
    super.key,
    this.music,
    this.imageUrl,
    this.size = 200.0,
    this.borderWidth = 0.0,
    this.borderColor,
    this.showShadow = true,
    this.onTap,
    this.enableHeroAnimation = false,
    this.heroTag,
  });

  @override
  Widget build(BuildContext context) {
    final effectiveImageUrl = imageUrl ?? music?.albumArt;

    Widget coverWidget = Container(
      width: size,
      height: size,
      decoration: BoxDecoration(
        shape: BoxShape.circle,
        border: borderWidth > 0
            ? Border.all(
                color: borderColor ?? Colors.white,
                width: borderWidth,
              )
            : null,
        boxShadow: showShadow
            ? [
                BoxShadow(
                  color: Colors.black.withOpacity(0.3),
                  blurRadius: 20,
                  offset: const Offset(0, 10),
                ),
              ]
            : null,
      ),
      child: ClipOval(
        child: _buildImageContent(context, effectiveImageUrl),
      ),
    );

    // 如果启用英雄动画，包装 Hero 组件
    if (enableHeroAnimation && heroTag != null) {
      coverWidget = Hero(
        tag: heroTag!,
        child: coverWidget,
      );
    }

    // 如果有点击回调，包装 GestureDetector
    if (onTap != null) {
      coverWidget = GestureDetector(
        onTap: onTap,
        child: coverWidget,
      );
    }

    return coverWidget;
  }

  /// 构建图片内容
  Widget _buildImageContent(BuildContext context, String? imageUrl) {
    if (imageUrl != null && imageUrl.isNotEmpty) {
      return CachedNetworkImage(
        imageUrl: imageUrl,
        fit: BoxFit.cover,
        placeholder: (context, url) => _buildPlaceholder(context),
        errorWidget: (context, url, error) => _buildErrorWidget(context),
        // 缓存配置
        cacheKey: imageUrl,
        memCacheWidth: size.toInt() * 2, // 2x 分辨率缓存
        memCacheHeight: size.toInt() * 2,
        maxWidthDiskCache: 600, // 更高分辨率的磁盘缓存
        maxHeightDiskCache: 600,
        // 渐入动画
        fadeInDuration: const Duration(milliseconds: 300),
        fadeOutDuration: const Duration(milliseconds: 100),
      );
    } else {
      return _buildPlaceholder(context);
    }
  }

  /// 构建占位符
  Widget _buildPlaceholder(BuildContext context) {
    return Container(
      decoration: BoxDecoration(
        shape: BoxShape.circle,
        color: Colors.grey.shade200,
      ),
      child: Center(
        child: Icon(
          Icons.music_note,
          size: size * 0.4,
          color: Colors.grey.shade400,
        ),
      ),
    );
  }

  /// 构建错误组件
  Widget _buildErrorWidget(BuildContext context) {
    return Container(
      decoration: BoxDecoration(
        shape: BoxShape.circle,
        color: Colors.grey.shade100,
      ),
      child: Center(
        child: Icon(
          Icons.broken_image,
          size: size * 0.3,
          color: Colors.grey.shade400,
        ),
      ),
    );
  }
}

/// 缩略图专辑封面组件
/// 适用于列表项等小尺寸显示场景
class ThumbnailAlbumCoverWidget extends StatelessWidget {
  /// 音乐数据
  final MusicItemModel? music;

  /// 图片URL
  final String? imageUrl;

  /// 组件大小
  final double size;

  /// 圆角半径
  final double borderRadius;

  const ThumbnailAlbumCoverWidget({
    super.key,
    this.music,
    this.imageUrl,
    this.size = 48.0,
    this.borderRadius = 4.0,
  });

  @override
  Widget build(BuildContext context) {
    final effectiveImageUrl = imageUrl ?? music?.albumArt;

    return Container(
      width: size,
      height: size,
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(borderRadius),
        color: Colors.grey.shade200,
      ),
      child: ClipRRect(
        borderRadius: BorderRadius.circular(borderRadius),
        child: effectiveImageUrl != null && effectiveImageUrl.isNotEmpty
            ? CachedNetworkImage(
                imageUrl: effectiveImageUrl,
                fit: BoxFit.cover,
                placeholder: (context, url) => _buildPlaceholder(),
                errorWidget: (context, url, error) => _buildPlaceholder(),
                // 缩略图缓存配置
                cacheKey: effectiveImageUrl,
                memCacheWidth: size.toInt(),
                memCacheHeight: size.toInt(),
                maxWidthDiskCache: 100, // 小尺寸磁盘缓存
                maxHeightDiskCache: 100,
              )
            : _buildPlaceholder(),
      ),
    );
  }

  /// 构建占位符
  Widget _buildPlaceholder() {
    return Center(
      child: Icon(
        Icons.music_note,
        size: size * 0.5,
        color: Colors.grey.shade400,
      ),
    );
  }
}
